import { isClosed } from "../utils/handle";
import type { UndertakeComposer, CallBack, ReactiverLike } from "../types";
import Composer from "./composer";

export default class Undertake extends Composer implements UndertakeComposer {
  private undertake?: CallBack<any, CallBack>;

  constructor(reactiver: ReactiverLike) {
    super(reactiver);
  }

  set(val: CallBack, caller: any = this): void {
    this.undertake = (params) => {
      return val.bind(caller, ...params);
    };
  }

  run(...args: Array<any>) {
    if (isClosed(this.reactiver)) {
      return undefined;
    }
    try {
      let result = this.undertake?.(args)();
      if (result === undefined && this.undertake) {
        throw new Error("Undertake must have a return!");
      }
      return result;
    } catch (err:any) {
      this.reactiver.closed = true;
      throw new Error(err.message || err);
  }
  }

  destroy(arg?: any): void {}
}
